﻿using Chloe;
using Chloe.MySql;
using ChloeUtil;
using Common;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Police.BLL
{
    public class SysMenuBLL
    {
        private MySqlContext context = MySqlUtil.context;
        private IQuery<SysMenu> q = MySqlUtil.context.Query<SysMenu>();

        public SysMenu GetById(int id)
        {
            SysMenu model = q.Where(a => a.MenuId == id).FirstOrDefault();
            return model;
        }

        public int Delete(SysMenu model)
        {
           int count = context.Delete<SysMenu>(model);
           return count;
        }

        public SysMenu Add(SysMenu model)
        {
            model = context.Insert<SysMenu>(model);
            return model;
        }

        public int Update(SysMenu model)
        {
            int count = context.Update<SysMenu>(model);
            return count;
        }

        public List<SysMenu> Get(string RoleIdStr)
        {
            string sql = string.Format("SELECT 	MenuId, MenuName, DispalyOrder, ParentId, MenuUrl, Remark, CreateTime, UpdateTime, MenuIcon FROM sys_menu WHERE MenuId IN (SELECT DISTINCT MenuId FROM sys_role_menu WHERE RoleId IN (SELECT RoleId FROM sys_role  WHERE RoleId IN({0})))", RoleIdStr);
            List<SysMenu> model = context.SqlQuery<SysMenu>(sql).ToList();
            return model;
        }

        public List<SysMenu> Get(int userId)
        {
            string sql = string.Format("SELECT 	MenuId, MenuName, DispalyOrder, ParentId, MenuUrl, Remark, CreateTime, UpdateTime, MenuIcon FROM sys_menu WHERE MenuId IN (SELECT DISTINCT MenuId FROM sys_role_menu WHERE RoleId IN (SELECT RoleId FROM sys_role  WHERE RoleId IN(SELECT RoleId FROM sys_user_role WHERE USERID={0})))", userId);
            List<SysMenu> model = context.SqlQuery<SysMenu>(sql).ToList();
            return model;
        }

        public List<TreeNode> GetTree()
        {
            List<SysMenu> models = q.Where(a => a.MenuId > 0).ToList();

            List<TreeNode> nodes = new List<TreeNode>();

            foreach (SysMenu item in models)
            {
                TreeNode node = new TreeNode();
                node.id = item.MenuId.ToString();
                node.pid = item.ParentId.ToString();
                node.text = item.MenuName;
                nodes.Add(node);
            }
            return nodes;
        }
    }
}
